<template>
  <div class="wallet-wrapper">
    <!-- 增强型Header -->
    <header class="enhanced-header">
      <div class="header-left" @click="back">
        <i class="fas fa-arrow-left"></i>
        <span class="back-text">返回</span>
      </div>
      <h1 class="header-title">我的钱包</h1>
    </header>

    <!-- 主体内容 -->
    <main class="wallet-main">
      <!-- 用户钱包信息 -->
      <div v-if="!isBusinessLoggedIn">
        <!-- 余额展示卡片 -->
        <div class="balance-card">
          <div class="balance-label">可用余额</div>
          <div class="balance-amount">
            <span class="currency">¥</span>
            <span class="amount">{{ balance.toFixed(2) }}</span>
          </div>
        </div>

        <!-- 核心操作按钮 -->
        <div class="action-grid">
          <button class="action-btn deposit" @click="showDepositDialog = true">
            <i class="fas fa-coins"></i>
            <span>充值</span>
          </button>
          <button class="action-btn withdraw" @click="showWithdrawDialog = true">
            <i class="fas fa-wallet"></i>
            <span>提现</span>
          </button>
          <button class="action-btn transfer" @click="showTransferDialog = true">
            <i class="fas fa-exchange-alt"></i>
            <span>转账</span>
          </button>
        </div>

        <!-- 信用信息面板 -->
        <div class="credit-panel">
          <div class="info-item">
            <span class="info-label">信用额度</span>
            <span class="info-value">¥{{ creditLimit.toFixed(2) }}</span>
          </div>
          <div class="info-divider"></div>
          <div class="info-item">
            <span class="info-label">未付账单</span>
            <span class="info-value">¥{{ outstandingBill.toFixed(2) }}</span>
          </div>
          <div class="info-divider"></div>
          <div class="info-item">
            <span class="info-label">违约金</span>
            <span class="info-value">¥{{ penaltyAmount.toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <!-- 商家钱包信息 -->
      <div v-if="isBusinessLoggedIn">
        <div class="balance-card">
          <div class="balance-label">商家可用余额</div>
          <div class="balance-amount">
            <span class="currency">¥</span>
            <span class="amount">{{ businessBalance.toFixed(2) }}</span>
          </div>
        </div>

        <div class="action-grid">
          <button class="action-btn deposit" @click="showBusinessDepositDialog = true">
            <i class="fas fa-coins"></i>
            <span>商家充值</span>
          </button>
          <button class="action-btn withdraw" @click="showBusinessWithdrawDialog = true">
            <i class="fas fa-wallet"></i>
            <span>商家提现</span>
          </button>
          <button class="action-btn transfer" @click="showBusinessTransferDialog = true">
            <i class="fas fa-exchange-alt"></i>
            <span>商家转账</span>
          </button>
        </div>
      </div>

      <!-- 用户转账弹窗 -->
      <div v-if="showTransferDialog" class="dialog-overlay">
        <div class="dialog-content">
          <h3 class="dialog-title">转账</h3>
          <input 
            type="number" 
            v-model="transferUserId" 
            placeholder="输入目标用户ID"
            class="dialog-input"
          >
          <input 
            type="number" 
            v-model="transferAmount" 
            placeholder="输入转账金额"
            class="dialog-input"
          >
          <div class="dialog-actions">
            <button class="confirm-btn" @click="transfer">确认转账</button>
            <button class="cancel-btn" @click="showTransferDialog = false">取消</button>
          </div>
        </div>
      </div>

      <!-- 商家转账弹窗 -->
      <div v-if="showBusinessTransferDialog" class="dialog-overlay">
        <div class="dialog-content">
          <h3 class="dialog-title">商家转账</h3>
          <input 
            type="number" 
            v-model="businessTransferUserId" 
            placeholder="输入目标用户ID"
            class="dialog-input"
          >
          <input 
            type="number" 
            v-model="businessTransferAmount" 
            placeholder="输入转账金额"
            class="dialog-input"
          >
          <div class="dialog-actions">
            <button class="confirm-btn" @click="businessTransfer">确认商家转账</button>
            <button class="cancel-btn" @click="showBusinessTransferDialog = false">取消</button>
          </div>
        </div>
      </div>

      <!-- 用户充值弹窗 -->
      <div v-if="showDepositDialog" class="dialog-overlay">
        <div class="dialog-content">
          <h3 class="dialog-title">充值金额</h3>
          <input 
            type="number" 
            v-model="depositAmount" 
            placeholder="输入充值金额"
            class="dialog-input"
          >
          <div class="dialog-actions">
            <button class="confirm-btn" @click="deposit">确认充值</button>
            <button class="cancel-btn" @click="showDepositDialog = false">取消</button>
          </div>
        </div>
      </div>

      <!-- 商家充值弹窗 -->
      <div v-if="showBusinessDepositDialog" class="dialog-overlay">
        <div class="dialog-content">
          <h3 class="dialog-title">商家充值金额</h3>
          <input 
            type="number" 
            v-model="businessDepositAmount" 
            placeholder="输入充值金额"
            class="dialog-input"
          >
          <div class="dialog-actions">
            <button class="confirm-btn" @click="businessDeposit">确认商家充值</button>
            <button class="cancel-btn" @click="showBusinessDepositDialog = false">取消</button>
          </div>
        </div>
      </div>

      <!-- 用户提现弹窗 -->
      <div v-if="showWithdrawDialog" class="dialog-overlay">
        <div class="dialog-content">
          <h3 class="dialog-title">提现金额</h3>
          <input 
            type="number" 
            v-model="withdrawAmount" 
            placeholder="输入提现金额"
            class="dialog-input"
          >
          <div class="dialog-actions">
            <button class="confirm-btn" @click="withdraw">确认提现</button>
            <button class="cancel-btn" @click="showWithdrawDialog = false">取消</button>
          </div>
        </div>
      </div>

      <!-- 商家提现弹窗 -->
      <div v-if="showBusinessWithdrawDialog" class="dialog-overlay">
        <div class="dialog-content">
          <h3 class="dialog-title">商家提现金额</h3>
          <input 
            type="number" 
            v-model="businessWithdrawAmount" 
            placeholder="输入提现金额"
            class="dialog-input"
          >
          <div class="dialog-actions">
            <button class="confirm-btn" @click="businessWithdraw">确认商家提现</button>
            <button class="cancel-btn" @click="showBusinessWithdrawDialog = false">取消</button>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部导航 -->
    <Footer />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import Footer from '../components/Footer.vue'

export default {
  name: 'Wallet',
  components: { Footer },
  setup() {
    const router = useRouter()
    // 从会话存储中获取用户和商家信息
    const user = JSON.parse(sessionStorage.getItem('user') || '{}');
    const userId = ref(user.userId || null);
    const business = JSON.parse(sessionStorage.getItem('business') || '{}');
    const businessId = ref(business.businessId || null);
    const isBusinessLoggedIn = ref(businessId.value ? true : false);

    // 用户钱包响应式数据
    const balance = ref(0)
    const creditLimit = ref(0)
    const outstandingBill = ref(0)
    const penaltyAmount = ref(0)
    const showDepositDialog = ref(false)
    const showWithdrawDialog = ref(false)
    const showTransferDialog = ref(false)
    const depositAmount = ref(null)
    const withdrawAmount = ref(null)
    const transferUserId = ref(null)
    const transferAmount = ref(null)

    // 商家钱包响应式数据
    const businessBalance = ref(0)
    const showBusinessDepositDialog = ref(false)
    const showBusinessWithdrawDialog = ref(false)
    const showBusinessTransferDialog = ref(false)
    const businessDepositAmount = ref(null)
    const businessWithdrawAmount = ref(null)
    const businessTransferUserId = ref(null)
    const businessTransferAmount = ref(null)

    // 初始化加载数据
    const loadWalletData = async () => {
      if (!userId.value && !businessId.value) {
        console.error('userId and businessId are undefined or null')
        return
      }

      try {
        // 根据登录类型加载数据
        let id = userId.value || businessId.value;
        const [creditLimRes, balanceRes, billRes, penaltyRes] = await Promise.all([
          axios.get(`/WalletController/credit-limit/${id}`),
          axios.get(`/WalletController/balance/${id}`),
          axios.get(`/WalletController/outstanding-bill/${id}`),
          axios.get(`/WalletController/penalty/${id}`)
        ])
        
        if (!isBusinessLoggedIn.value) {
          creditLimit.value = creditLimRes.data.result
          balance.value = balanceRes.data.result
          outstandingBill.value = billRes.data.result
          penaltyAmount.value = penaltyRes.data.result
        } else {
          businessBalance.value = balanceRes.data.result
        }
      } catch (error) {
        console.error('数据加载失败:', error)
      }
    }

    // 充值操作
    const deposit = async () => {
      if (!userId.value) {
        alert('userId is undefined or null');
        return;
      }
    
      try {
        // 创建充值订单
        const VIRTUAL_BUSINESS_ID = 11001; // 虚拟商家ID
        const VIRTUAL_DELIVERY_ADDRESS_ID = 1001; // 虚拟配送地址ID
        let url = `OrdersController/createOrders/${userId.value}/${VIRTUAL_BUSINESS_ID}/${VIRTUAL_DELIVERY_ADDRESS_ID}/${depositAmount.value}`;
        const response = await axios.post(url);
    
        const orderId = response.data.result;
        if (orderId > 0) {
          // 跳转到支付页面
          router.push({
            path: '/payment',
            query: {
              orderId: orderId,
              userId: userId.value,
              reduction: 0 // 充值没有积分抵扣
            }
          });
          showDepositDialog.value = false;
        } else {
          alert('创建充值订单失败！');
        }
      } catch (error) {
        console.error('创建充值订单错误:', error);
        alert('创建充值订单时发生错误');
      }
    };

    // 商家充值操作
    const businessDeposit = async () => {
      if (!businessId.value) {
        alert('businessId is undefined or null');
        return;
      }
    
      try {
        // 创建商家充值订单
        const VIRTUAL_BUSINESS_ID = 11001; // 虚拟商家ID
        const VIRTUAL_DELIVERY_ADDRESS_ID = 1001; // 虚拟配送地址ID
        let url = `OrdersController/createOrders/${businessId.value}/${VIRTUAL_BUSINESS_ID}/${VIRTUAL_DELIVERY_ADDRESS_ID}/${businessDepositAmount.value}`;
        const response = await axios.post(url);
    
        const orderId = response.data.result;
        if (orderId > 0) {
          // 跳转到支付页面
          router.push({
            path: '/payment',
            query: {
              orderId: orderId,
              businessId: businessId.value,
              reduction: 0 // 充值没有积分抵扣
            }
          });
          showBusinessDepositDialog.value = false;
        } else {
          alert('创建商家充值订单失败！');
        }
      } catch (error) {
        console.error('创建商家充值订单错误:', error);
        alert('创建商家充值订单时发生错误');
      }
    };

    // 提现操作
    const withdraw = async () => {
      if (!userId.value) {
        alert('userId is undefined or null');
        return;
      }
      if (!withdrawAmount.value || withdrawAmount.value <= 0) {
        alert('请输入有效的提现金额');
        return;
      }
      if (withdrawAmount.value > balance.value) {
        alert('提现金额不能超过可用余额');
        return;
      }

      try {
        // 提现操作（通过传递负数金额实现）
        const response = await axios.post(`/WalletController/deposit/${userId.value}/${-withdrawAmount.value}`, {}, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });

        if (response.data.result === "充值成功") {
          // 更新余额
          balance.value = balance.value - withdrawAmount.value;
          alert('提现成功！');
          showWithdrawDialog.value = false;
        } else {
          alert('提现失败！');
        }
      } catch (error) {
        console.error('提现错误:', error);
        alert('提现时发生错误');
      }
    };

    // 商家提现操作
    const businessWithdraw = async () => {
      if (!businessId.value) {
        alert('businessId is undefined or null');
        return;
      }
      if (!businessWithdrawAmount.value || businessWithdrawAmount.value <= 0) {
        alert('请输入有效的提现金额');
        return;
      }
      if (businessWithdrawAmount.value > businessBalance.value) {
        alert('提现金额不能超过可用余额');
        return;
      }

      try {
        // 商家提现操作（通过传递负数金额实现）
        const response = await axios.post(`/WalletController/deposit/${businessId.value}/${-businessWithdrawAmount.value}`, {}, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });

        if (response.data.result === "充值成功") {
          // 更新商家余额
          businessBalance.value = businessBalance.value - businessWithdrawAmount.value;
          alert('商家提现成功！');
          showBusinessWithdrawDialog.value = false;
        } else {
          alert('商家提现失败！');
        }
      } catch (error) {
        console.error('商家提现错误:', error);
        alert('商家提现时发生错误');
      }
    };

    // 转账操作
    const transfer = async () => {
      if (!userId.value) {
        alert('userId is undefined or null');
        return;
      }
      if (!transferUserId.value || !transferAmount.value || transferAmount.value <= 0) {
        alert('请输入有效的目标用户ID和转账金额');
        return;
      }
      if (transferAmount.value > balance.value) {
        alert('转账金额不能超过可用余额');
        return;
      }

      try {
        // 从当前账户扣款
        const withdrawResponse = await axios.post(`/WalletController/deposit/${userId.value}/${-transferAmount.value}`, {}, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });

        if (withdrawResponse.data.result !== "充值成功") {
          alert('转账失败！');
          return;
        }

        // 向目标用户账户存款
        const depositResponse = await axios.post(`/WalletController/deposit/${transferUserId.value}/${transferAmount.value}`, {}, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });

        if (depositResponse.data.result === "充值成功") {
          // 更新余额
          balance.value = balance.value - transferAmount.value;
          alert('转账成功！');
          showTransferDialog.value = false;
        } else {
          alert('转账失败！');
        }
      } catch (error) {
        console.error('转账错误:', error);
        alert('转账时发生错误');
      }
    };

    // 商家转账操作
    const businessTransfer = async () => {
      if (!businessId.value) {
        alert('businessId is undefined or null');
        return;
      }
      if (!businessTransferUserId.value || !businessTransferAmount.value || businessTransferAmount.value <= 0) {
        alert('请输入有效的目标用户ID和转账金额');
        return;
      }
      if (businessTransferAmount.value > businessBalance.value) {
        alert('转账金额不能超过可用余额');
        return;
      }

      try {
        // 从当前商家账户扣款
        const withdrawResponse = await axios.post(`/WalletController/deposit/${businessId.value}/${-businessTransferAmount.value}`, {}, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });

        if (withdrawResponse.data.result !== "充值成功") {
          alert('商家转账失败！');
          return;
        }

        // 向目标用户账户存款
        const depositResponse = await axios.post(`/WalletController/deposit/${businessTransferUserId.value}/${businessTransferAmount.value}`, {}, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });

        if (depositResponse.data.result === "充值成功") {
          // 更新商家余额
          businessBalance.value = businessBalance.value - businessTransferAmount.value;
          alert('商家转账成功！');
          showBusinessTransferDialog.value = false;
        } else {
          alert('商家转账失败！');
        }
      } catch (error) {
        console.error('商家转账错误:', error);
        alert('商家转账时发生错误');
      }
    };

    // 生命周期钩子
    onMounted(loadWalletData)

    return {
      balance,
      creditLimit,
      outstandingBill,
      penaltyAmount,
      showDepositDialog,
      showWithdrawDialog,
      showTransferDialog,
      showBusinessDepositDialog,
      showBusinessWithdrawDialog,
      showBusinessTransferDialog,
      depositAmount,
      withdrawAmount,
      transferUserId,
      transferAmount,
      businessDepositAmount,
      businessWithdrawAmount,
      businessTransferUserId,
      businessTransferAmount,
      deposit,
      withdraw,
      transfer,
      businessDeposit,
      businessWithdraw,
      businessTransfer,
      isBusinessLoggedIn,
      businessBalance,
      back: () => router.push('/my')
    }
  }
}
</script>

<style scoped>
	/* 添加提现相关的样式 */
	.dialog-overlay {
	  position: fixed;
	  top: 0;
	  left: 0;
	  right: 0;
	  bottom: 0;
	  background-color: rgba(0, 0, 0, 0.5);
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  z-index: 1000;
	}
	
	.dialog-content {
	  background-color: white;
	  padding: 20px;
	  border-radius: 8px;
	  width: 80%;
	  max-width: 400px;
	}
	
	.dialog-title {
	  margin-top: 0;
	  margin-bottom: 15px;
	}
	
	.dialog-input {
	  width: 100%;
	  padding: 10px;
	  margin-bottom: 15px;
	  border: 1px solid #ddd;
	  border-radius: 4px;
	}
	
	.dialog-actions {
	  display: flex;
	  justify-content: flex-end;
	}
	
	.confirm-btn, .cancel-btn {
	  padding: 8px 16px;
	  border: none;
	  border-radius: 4px;
	  cursor: pointer;
	  margin-left: 10px;
	}
	
	.confirm-btn {
	  background-color: #38CA73;
	  color: white;
	}
	
	.cancel-btn {
	  background-color: #f1f1f1;
	  color: #333;
	}
	
	/* 其他样式 */
	.balance-card {
	  background-color: #f9f9f9;
	  padding: 20px;
	  border-radius: 8px;
	  margin: 15px;
	}
	
	.balance-label {
	  font-size: 14px;
	  color: #666;
	}
	
	.balance-amount {
	  font-size: 24px;
	  font-weight: bold;
	  margin-top: 5px;
	}
	
	.currency {
	  color: #666;
	  font-size: 16px;
	}
	
	.amount {
	  color: #333;
	}
	
	.action-grid {
	  display: flex;
	  justify-content: space-around;
	  margin: 20px 0;
	}
	
	.action-btn {
	  background-color: transparent;
	  border: none;
	  font-size: 16px;
	  cursor: pointer;
	  display: flex;
	  flex-direction: column;
	  align-items: center;
	}
	
	.action-btn i {
	  font-size: 24px;
	  margin-bottom: 5px;
	}
	
	.action-btn.deposit i {
	  color: #38CA73;
	}
	
	.action-btn.withdraw i {
	  color: #FF9500;
	}
	
	.action-btn.transfer i {
	  color: #007AFF;
	}
	
	.credit-panel {
	  background-color: #f9f9f9;
	  padding: 15px;
	  border-radius: 8px;
	  margin: 15px;
	}
	
	.info-item {
	  display: flex;
	  justify-content: space-between;
	  padding: 10px 0;
	}
	
	.info-divider {
	  height: 1px;
	  background-color: #eee;
	  margin: 5px 0;
	}
/* 增强型Header样式 */
.enhanced-header {
  padding: 1.5rem;
  display: flex;
  align-items: center;
  background: #ffffff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  cursor: pointer;
}

.fa-arrow-left {
  font-size: 2rem !important;
  color: #007bff;
}

.back-text {
  font-size: 1.2rem;
  color: #007bff;
}

.header-title {
  margin-left: 2rem;
  font-size: 1.8rem;
  color: #333;
}

/* 余额卡片 */
.balance-card {
  background: linear-gradient(135deg, #007bff, #00bfff);
  padding: 2rem;
  border-radius: 16px;
  margin: 2rem;
  color: white;
}

.balance-label {
  font-size: 1.4rem;
  margin-bottom: 0.5rem;
}

.balance-amount {
  display: flex;
  align-items: baseline;
}

.currency {
  font-size: 2.5rem;
  margin-right: 0.5rem;
}

.amount {
  font-size: 3.5rem;
  font-weight: 700;
}

/* 操作按钮组 */
.action-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1.5rem;
  margin: 2rem;
}

.action-btn {
  padding: 1.5rem;
  border-radius: 12px;
  border: none;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.8rem;
  font-size: 1.2rem;
  transition: transform 0.2s;
}

.action-btn i {
  font-size: 2rem !important;
}

.deposit { background: #28a745; color: white; }
.withdraw { background: #17a2b8; color: white; }
.transfer { background: #ffc107; color: black; }

/* 信用信息面板 */
.credit-panel {
  background: white;
  border-radius: 16px;
  margin: 2rem;
  padding: 1.5rem;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 1.2rem 0;
  font-size: 1.2rem;
}

.info-label {
  color: #666;
}

.info-value {
  font-weight: 600;
  color: #333;
}

.info-divider {
  height: 1px;
  background: #eee;
  margin: 0.5rem 0;
}

/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-content {
  background: white;
  padding: 2rem;
  border-radius: 16px;
  width: 90%;
  max-width: 300px;
}

.dialog-title {
  font-size: 1.5rem;
  margin-bottom: 1.5rem;
}

.dialog-input {
  width: 90%;
  padding: 1.2rem;
  font-size: 1.2rem;
  border: 2px solid #007bff;
  border-radius: 8px;
  margin-bottom: 1.5rem;
}

.dialog-actions {
  display: flex;
  gap: 1rem;
}

.confirm-btn, .cancel-btn {
  flex: 1;
  padding: 1rem;
  border: none;
  border-radius: 8px;
  font-size: 1.2rem;
}

.confirm-btn {
  background: #007bff;
  color: white;
}

.cancel-btn {
  background: #eee;
  color: #666;
}
</style>